package com.xz.stu.server.job;

import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;

@Component
public class DynamicScheduledTask {

    private final ThreadPoolTaskScheduler taskScheduler;
    private final Map<String, ScheduledFuture<?>> scheduledFutures = new HashMap<>();

    public DynamicScheduledTask(ThreadPoolTaskScheduler taskScheduler) {
        this.taskScheduler = taskScheduler;
    }

    public void addTask(String taskId, String cronExpression, Runnable task) {
        ScheduledFuture<?> future = taskScheduler.schedule(task, new CronTrigger(cronExpression));
        scheduledFutures.put(taskId, future);
    }

    public void removeTask(String taskId) {
        ScheduledFuture<?> future = scheduledFutures.get(taskId);
        if (future != null) {
            future.cancel(true);
            scheduledFutures.remove(taskId);
        }
    }

    public boolean isTaskExists(String taskId) {
        return scheduledFutures.containsKey(taskId);
    }
}
